<template>
<div class="spike-marketing-add views-container">
    <el-dialog :visible.sync="dialogVisibleImg" width="50%" custom-class="reset-pwd wlm-form-dialog dialog-table">
        <div class="wlm-form">
            <div class="wlm-form-header wlm-dialog-fixheader">
                <span class="wlm-dialog-inlenr">活动标签</span>
            </div>
            <div class="flex-row flex-justify-c" style="margin:20px 0">
                <img height="600" :src="getPath('miaosha.jpg')" alt="">
            </div>
            </div>
    </el-dialog>
    <el-dialog width="60%" :visible.sync="dialogTableVisible" custom-class="reset-pwd wlm-form-dialog dialog-table">
        <div class="wlm-form" v-if="dialogTableVisible">
            <div class="wlm-form-header wlm-dialog-fixheader">
                <span class="wlm-dialog-inlenr">设置拼团</span>
            </div>
            <el-scrollbar wrap-class="scrollbar-wrapper">
                <div class="wlm-form-content">
                    <div class="wlm-dialog-main">
                        <div class="wlm-dialog-content" v-if="formFormatData.formData.goods[$index]">
                            <div class="flex-row flex-align-c" style="margin-bottom:10px;">
                                <span style="margin-right:10px;">当前商品</span>
                                <img style="margin:0 6px;" height="50" width="50" :src="imgPath" alt="">
                                <p>{{goodsName}}</p>
                            </div>
                            <el-table :data="formFormatData.formData.goods[$index]['attr']" style="width: 100%">
                                <el-table-column prop="date" label="商品规格">
                                    <template slot-scope="scope">
                                        <p>{{scope.row.title}}</p>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="date" label="价格">
                                    <template slot-scope="scope">
                                        <p>{{scope.row.goods_price}}</p>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="date" label="库存">
                                    <template slot-scope="scope">
                                        <p>{{scope.row.stock_num}}</p>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="name" label="拼团价">
                                    <template slot-scope="scope">
                                        <el-input-number :controls="false"  :precision="2" class="wlm-input-auto" v-model="scope.row.groups_price" :max="((scope.row.goods_price * 100) - 1)/100" :min="0"></el-input-number>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="name" label="拼团库存">
                                    <template slot-scope="scope">
                                        <el-input-number :controls="false" class="wlm-input-auto" v-model="scope.row.groups_stock" :min="0" :precision="0" ></el-input-number>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="name" label="是否拼团">
                                    <template slot-scope="scope">
                                        <el-switch :active-value="1" :inactive-value="2" v-model="scope.row.is_use">
                                        </el-switch>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>
                </div>
            </el-scrollbar>
        </div>
        <footer class="flex-row flex-align-c flex-justify-c wlm-dialog-fixfooter">
            <el-button size="small" type="primary" @click="dialogTableVisible = false">确定</el-button>
        </footer>
    </el-dialog>
    <div class="wlm-form">
        <div class="wlm-form-header">{{`${isFormEdit?'编辑':'添加'}拼团`}}</div>
        <div class="wlm-form-content">
            <el-form :ref="formFormatData.key"  :model="formFormatData.formData" :rules="formFormatData.rules" size="small" label-width="120px" class="retail-form" label-position="right">
                <el-form-item label="活动名称" prop="title">
                    <el-input :disabled="$hasFormEnd" v-model.trim="formFormatData.formData.title">
                    </el-input>
                </el-form-item>
                <el-form-item label="活动时间" prop="time">
                    <el-date-picker :disabled="$hasFormEdit" style="width:360px;" :default-time="[`${new Date().getHours()}:${(new Date().getMinutes() + 5).toString().padStart(2,'0')}:00`,'23:59:59']" :picker-options="afterOptions" v-model="formFormatData.formData.time" value-format="timestamp" type="datetimerange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="参团人数">
                     <el-input-number v-model="formFormatData.formData.join_num" :controls="false" controls-position="right" :min="2" :max="100"></el-input-number>
                </el-form-item>
                <el-form-item label="每人限购">
                    <el-checkbox :disabled="$hasFormEdit" v-model="formFormatData.formData.is_limit" :true-label="1" :false-label="0">用户每次商品购买数量限制为1，此限制是对用户开团以及参团的次数限制</el-checkbox>
                    <div class="form-help">每个商品购买的数量限制</div>
                </el-form-item>
                <el-form-item label="限购数量" v-if="formFormatData.formData.is_limit == '1'">
                     <el-input-number @change="newGiftChange(formFormatData.formData,'limit_num')" :disabled="$hasFormEdit"  :precision="0"  v-model="formFormatData.formData.limit_num" :controls="false"  :min="1"></el-input-number>
                </el-form-item>
                <el-form-item label="拼团渠道" prop="channel">
                  <el-checkbox-group v-model="formFormatData.formData.channel" :disabled="$hasFormEnd">
                    <el-checkbox label="2" v-if="JSON.stringify($store.getters.power).indexOf('wxapp')>-1">微信小程序</el-checkbox>
                  <el-checkbox label="3" v-if="JSON.stringify($store.getters.power).indexOf('H5')>-1">H5</el-checkbox>
                  <el-checkbox label="4" v-if="JSON.stringify($store.getters.power).indexOf('wechat')>-1">微信公众号</el-checkbox>
                  <el-checkbox label="7" v-if="JSON.stringify($store.getters.power).indexOf('aliapp')>-1">支付宝小程序</el-checkbox>
                  <el-checkbox label="9" v-if="JSON.stringify($store.getters.power).indexOf('toutiaoapp')>-1">抖音-头条</el-checkbox>
                        <!-- <el-checkbox label="2" v-if="$store.getters.power.includes('wxapp')">微信小程序</el-checkbox>
                        <el-checkbox label="3" v-if="$store.getters.power.includes('H5')">H5</el-checkbox>
                        <el-checkbox label="4" v-if="$store.getters.power.includes('wechat')">微信公众号</el-checkbox>
                        <el-checkbox label="7" v-if="$store.getters.power.includes('aliapp')">支付宝小程序</el-checkbox>
                        <el-checkbox label="9" v-if="$store.getters.power.includes('toutiaoapp')">抖音-头条</el-checkbox> -->
                  </el-checkbox-group>
                </el-form-item>
                <el-form-item label="拼团标签" prop="tags">
                    <el-input :disabled="$hasFormEnd" style="display: block;" v-model="formFormatData.formData.tags">
                    </el-input>
                    <div><span class="form-help">展示在商品详情页 </span>
                        <el-button type="text" @click="dialogVisibleImg = true">点击查看示例</el-button>
                    </div>
                </el-form-item>
                <el-form-item label="拼团时间" prop="join_time">
                    <el-input-number class="wlm-input-auto" :min="0" :max="999" :precision="0" :controls="false" v-model.trim="formFormatData.formData.join_time[0]" style="width:60px;">
                    </el-input-number>
                    <span>时</span>
                    <el-input-number class="wlm-input-auto" :min="0" :max="60" :precision="0" :controls="false" v-model.trim="formFormatData.formData.join_time[1]" style="width:60px;">
                    </el-input-number>
                    <span>分</span>
                    <el-input-number class="wlm-input-auto" :min="0" :max="60" :precision="0" :controls="false" v-model.trim="formFormatData.formData.join_time[2]" style="width:60px;">
                    </el-input-number>
                    <span>秒</span>
                </el-form-item>
                <el-form-item label="是否分销">
                    <el-radio-group :disabled="$hasFormEnd" v-model="formFormatData.formData.is_dealer">
                        <el-radio :label="1">分销</el-radio>
                        <el-radio :label="0">不分销</el-radio>
                    </el-radio-group>
                    <div class="form-help">分销商品是否还参与分销</div>
                </el-form-item>
                <el-form-item label="分销模式">
                    <el-radio-group  v-model="formFormatData.formData.dealer_mode">
                        <el-radio :label="1">分销默认设置</el-radio>
                        <el-radio :label="2">商品单独设置</el-radio>
                    </el-radio-group>
                </el-form-item>
                <!-- <el-form-item label="社群服务">
                  <el-select v-model="formFormatData.formData.community_type" placeholder="请选择客服类型" class="poster" @change="communitybtn">
                      <el-option :label="'社群'" :value="1">
                      </el-option>
                      <el-option :label="'客服'" :value="2">
                      </el-option>
                      <el-option :label="'公众号'" :value="3">
                      </el-option>
                      <el-option :label="'电话'" :value="4">
                      </el-option>
                  </el-select>
                   <el-select v-model="formFormatData.formData.community_id" placeholder="请选择" style="width:200px;"  v-if="!!formFormatData.formData.community_type">
                    <el-option v-for="(item,index) in selectValue" :key="index" :label="item.title" :value="item.id" ></el-option>
                  </el-select>
              </el-form-item> -->
                <el-form-item label="凑团设置">
                    <el-checkbox :disabled="$hasFormEnd" v-model="formFormatData.formData.is_show_groups" :true-label="1" :false-label="0">开启凑团</el-checkbox>
                    <div class="form-help">开启凑团后,对于未参团的买家,活动商品详情页会显示未成团的团列表,买家可以任意选一个参团,提升参团率</div>
                </el-form-item>
                <el-form-item label="模拟成团">
                    <el-checkbox :disabled="$hasFormEnd" v-model="formFormatData.formData.is_auto_groups" :true-label="1" :false-label="0">开启模拟成团</el-checkbox>
                    <div class="form-help">开启模拟成团后,拼团有效期内人数未满的团,系统将会模拟"匿名买家"凑满人数,使该团成团,只是对已经付款的买家发货,请谨慎处理</div>
                </el-form-item>
                <el-form-item label="团长优惠">
                    <el-checkbox :disabled="$hasFormEnd" v-model="formFormatData.formData.is_commander_discount" :true-label="1" :false-label="0">开启团长优惠</el-checkbox>
                    <div class="form-help">开启团长优惠后,团长享受更优惠的拼团价格,有利于提高开团率或者成团率</div>
                </el-form-item>
                <el-form-item label="" v-if="formFormatData.formData.is_commander_discount=='1'">
                    <div class="input-slot flex-row flex-align-c flex-justify-s wlm-input-appendbox">
                        <el-input-number :controls="false" :min="0" :disabled="$hasFormEnd" :precision="2" v-model="formFormatData.formData.commander_discount"></el-input-number>
                        <!-- <el-input  :min="0" v-model="formFormatData.formData.commander_discount"></el-input> -->
                        <div class="wlm-input-append append-right">元</div>
                    </div>
                </el-form-item>
                <el-form-item label="自定义分享图片">
                    <el-radio-group v-model="formFormatData.formData.activity_share">
                        <el-radio :label="10">默认分享卡</el-radio>
                        <el-radio :label="20">自定义分享卡</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="分享图片" ref="businessbackgroundmap" v-if="formFormatData.formData.activity_share==20">
                    <choose-files ref="chooseFiles" :config="chooseBgConfig" :changeEvt="formFormatFiltersChange"></choose-files>
                    <div class="form-help">推荐尺寸：750X750，尺寸不匹配时，图片将选取部分展示</div>
                </el-form-item>
                <el-form-item label="" prop="custom_share_content">
                    <div class="flex-col">
                        <el-checkbox :true-label="20" :false-label="10" v-model="formFormatData.formData.is_custom">自定义分享文案</el-checkbox>
                        <el-input v-if="formFormatData.formData.is_custom==20" placeholder="请输入分享文案" v-model="formFormatData.formData.custom_share_content" style="width:80%;">
                        </el-input>
                    </div>
                </el-form-item>
                <el-form-item label="活动商品" prop="goods">
                    <choose-goods ref="chooseGoods" :config="chooseGoodsConfig" :changeEvt="filtersChange"></choose-goods>
                    <el-button type="primary" @click="goodsToogle">拼团商品</el-button>
                    <div class="form-help">选择参加拼团的商品</div>

                    <el-table v-if="formFormatData.formData.goods!=''" :data="formFormatData.formData.goods" style="width: 100%">
                        <el-table-column prop="date" label="商品">
                            <template slot-scope="scope">
                                <div class="flex-row">
                                    <img class="logo" v-if="scope.row.image && scope.row.image[0]" :src="scope.row.image[0]['file_path']">
                                    <div class="inner-text">
                                        <p>{{scope.row.goods_name}}</p>
                                        <span>￥:{{scope.row.attr[0]['goods_price']}}</span>
                                    </div>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="date" label="库存">
                            <template slot-scope="scope">
                                <p>{{scope.row.stock_num || scope.row.stock}}</p>
                            </template>
                        </el-table-column>
                        <el-table-column prop="name" label="拼团设置">
                            <template slot-scope="scope">
                                <div v-if="scope.row.attr && scope.row.attr[0]['spec_id']!=-1">
                                    <el-button  plain @click="showDialog(scope,scope.row.image[0]['file_path'],scope.row.goods_name)">设置拼团价与库存</el-button>
                                </div>
                                <div v-if="scope.row.attr && scope.row.attr[0]['spec_id']==-1" class="flex-row">
                                  <div class="flex-col">
                                    <p class="orders-gray font-12">拼团价</p>
                                    <el-input-number class="wlm-input-auto" :precision="2" :min="0" @change="newGiftChange(scope.row.attr[0],'groups_price',0.01)" :controls="false" :disabled="$hasFormEnd" v-model.number="scope.row.attr[0]['groups_price']" style="width:100px;" :max="((Number(scope.row.attr[0]['goods_price']) * 100) - 1)/100"></el-input-number>
                                  </div>
                                  <div class="flex-col" style="margin-left:20px;">
                                    <p class="orders-gray font-12">拼团库存</p>
                                    <el-input-number class="wlm-input-auto" :precision="0" :min="0" @change="newGiftChange(scope.row.attr[0],'groups_stock')" :controls="false" :disabled="$hasFormEnd" v-model.number="scope.row.attr[0]['groups_stock']" style="width:100px;"></el-input-number>
                                  </div>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="date" label="虚拟销量">
                            <template slot-scope="scope">
                              <el-input-number :precision="0"  :min="0" @change="oldGiftChange(scope.row,'virtual_sales')" class="wlm-input-auto" :controls="false"  v-model="scope.row.virtual_sales" style="width:100px;"></el-input-number>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" >
                            <template slot-scope="scope">
                                <div class="operation-group">
                                    <el-button :disabled="$hasFormEnd" class="wlm-text" type="text" @click="deleteTable(scope)">删除</el-button>
                                </div>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-form-item>
            </el-form>
        </div>
    </div>
    <div v-cloak class="wlm-fixed-btn flex-row flex-align-c flex-justify-c">
        <el-button size="small" @click="formFormatSubmit({ router: { type: 'replace', path: '/application/groupsMarketing', code: 1 }})" type="primary" :loading="loading">保存</el-button>
        <router-link tag="span" to="/application/groupsMarketing">
            <el-button size="small">返回</el-button>
        </router-link>
    </div>
</div>
</template>

<script>
import ChooseGoods from '@/components/ChooseGoods/index'
import ChooseFiles from '@/components/ChooseFiles/index'
import {
  addGroups,
  getGroupsData
} from '@/api/application'
import {
  servicesList
} from '@/api/merchant'
import mixins from '@/mixins/mixins'
export default {
  mixins: [mixins.getters('Form')],
  name: 'SpikeMarketingAdd',
  components: {
    ChooseGoods,
    ChooseFiles
  },
  computed: {
    getPath() {
      return function(path) {
        return (path.includes('https://') || path.includes('http://')) ? `${path}` : require(`@/assets/custorm_style/${path}`)
      }
    },
    $hasFormEdit() {
      return this.isFormEdit && this.formFormatData.formData.status !== 4
    },
    $hasFormEnd() {
      return this.isFormEdit && this.formFormatData.formData.status === 3
    }
  },
  data() {
    var checkTime = (rule, value, callback) => {
      const { message } = rule
      const time = this.formFormatData.formData.time
      if ((Array.isArray(time) && time.length === 0) || !Array.isArray(time)) {
        return callback(new Error(`${message}！~`))
      } else {
        callback()
      }
    }

    var checkGoods = (rule, value, callback) => {
      const { message } = rule
      const goods = this.formFormatData.formData.goods
      if (Array.isArray(goods) && goods.length === 0) {
        return callback(new Error(`${message}！~`))
      } else {
        callback()
      }
    }

    var checkJoinTime = (rule, value, callback) => {
      const { message } = rule
      const join_time = this.formFormatData.formData.join_time
      if (Array.isArray(join_time) && join_time.length === 0 || (Array.isArray(join_time) && join_time.includes(''))) {
        return callback(new Error(`${message}！~`))
      } else {
        callback()
      }
    }
    return {
      selectValue:[],
      loading: false,
      $index: -1,
      dialogTableVisible: false,
      dialogVisibleImg: false,
      imgPath: '',
      goodsName: '',
      currentRow: [],
      chooseBgConfig: {
        type: ['image'],
        model: 'display',
        uploadConfig: {
          limit: 1,
          isMore: true,
          model: 'display'
        },
        isUnique: true,
        initList: [],
        isShowList: true,
        file_type: 'image',
        bindKey: {
          key: 'share_image_id',
          model: 'img'
        }
      },
      chooseGoodsConfig: {
        type: ['chooseGoods'],
        model: 'normal',
        params: {
          indexType: 'groups'
        },
        collage: 'collages',
        disabled: [{
          label: 'sale_type',
          value: 0,
          reverse: true
        }, {
          label: 'member_exclusive',
          value: 1
        }, {
          label: 'transport_type',
          value: 30
        }],
        initList: []
      },
      platformConfig: {
        type: ['image'],
        initList: [],
        isMore: false,
        bindKey: {
          key: 'image',
          model: 'img'
        }
      },
      chooseData: [],
      formFormatData: {
        key: 'userForm',
        model: {
          noCreateEdit: false,
          bindDialog: 'dialogTableVisible'
        },
        api: {
          editForm: {
            api: getGroupsData,
            params: {
              id: ''
            },
            filters: {
              choose: {
                bindInit: ['chooseGoodsConfig']
              },
              img: {
                bindInit: ['chooseBgConfig']
              }
            },
            redirect: 'groups_id'
          },
          submitForm: addGroups
        },
        formData: {
          status: '',
          title: '',
          time: [],
          join_num: '',
          is_limit: '0',
          join_time: ['24', '0', '0'],
          is_dealer: 1,
          dealer_mode: 1,
          is_auto_groups: '0',
          is_show_groups: '0',
          community_type:'',
          community_id:'',
          is_commander_discount: '0',
          tags: '拼团',
          channel: [],
          commander_discount: '',
          limit_num: '',
          goods: [],
          activity_share: 10,
          share_image_id: [],
          is_custom: 10,
          custom_share_content: ''
        },
        rules: {
          title: [{
            message: '请填写活动名称',
            required: true,
            trigger: 'change'
          }],
          channel: [{
            message: '请填写活动渠道',
            required: true,
            trigger: 'change'
          }],
          time: [{
            message: '请选择活动时间',
            required: true,
            validator: checkTime,
            trigger: 'change'
          }],
          tags: [{
            message: '请填写拼团标签',
            required: true,
            trigger: 'change'
          }],
          join_time: [{
            message: '请填写拼团时间',
            required: true,
            validator: checkJoinTime,
            trigger: 'change'
          }],
          goods: [{
            message: '请选择活动商品',
            required: true,
            validator: checkGoods,
            trigger: 'change'
          }],
          custom_share_content: [{
            min: 4,
            max: 20,
            message: '请输入4-20个字的分享文案',
            trigger: 'blur'
          }]
        }
      }
    }
  },
  methods: {
    // communitybtn(val){
    //   servicesList({list_rows: 'all' }).then(res=>{
    //     this.selectValue = res.data.data
    //   })
    // },
    oldGiftChange(params, key) {
      this.$nextTick(() => {
        params[key] = String(params[key]).replace(/[^\d]/g, '')
      })
    },
    inputchange(scope, goods_price, groups_price) {
      if (isNaN(Number(groups_price))) {
        // this.formFormatData.formData.goods[scope.$index]['attr'][0].push({ groups_price: '' })
        console.log(this.formFormatData.formData.goods[scope.$index]['attr'])
      } else {
        console.log('this.luck_title')
      }
    },
    filtersChange(val) {
      this.currentRow = val.currentRow
      const displayData = val.displayData
      displayData.map(item => {
        item.attr = JSON.parse(JSON.stringify([...[], ...item.sku]))
        item.virtual_sales = '0'
        item.attr.map(attritem => {
          if (item.spec_type === 10) {
            attritem.spec_id = -1
          } else if (item.spec_type === 20) {
            attritem.spec_id = attritem.goods_sku_id
          }
          attritem.groups_price = ''
          attritem.is_use = 1
        })
      })
      displayData.map(item => {
        var hasIndex = this.formFormatData.formData.goods.findIndex(tableitem => { return tableitem.goods_id === item.goods_id })
        if (hasIndex === -1) {
          console.log(item, 'filtersChange')
          this.formFormatData.formData.goods.push(item)
        }
      })
    },
    goodsToogle() {
      const result = []
      this.formFormatData.formData.goods.map(item => {
        result.push(item.goods_id)
      })
      this.$refs.chooseGoods.currentRow = result
      this.$refs.chooseGoods.toggle()
    },
    deleteTable(scope) {
      this.formFormatData.formData.goods.splice(scope.$index, 1)
      this.currentRow.splice(scope.$index, 1)
    },
    showDialog(scope, img, name) {
      if (scope) {
        this.$index = scope.$index
        this.imgPath = img
        this.goodsName = name
        this.dialogTableVisible = true
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.spike-marketing-add {
    .logo {
        height: 40px;
        width: 40px;
        border-radius: 50%;
        vertical-align: middle;
        margin-right: 6px;
    }
}
</style>
